<?php


namespace Beerus\Modules\Album\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\Album\AlbumCategoryModel;
use Biz\model\Album\AlbumCategoryRelateModel;
use Biz\model\Album\AlbumListModel;
use Biz\service\Album\AlbumCategoryService;
use Biz\service\Album\AlbumListService;
use Biz\service\Album\FormatAlbumService;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Exception;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class AlbumCateGoryController extends Controller
{
    const PAGE_SIZE = 20;

    public function indexPost(Request $request, $id): \Illuminate\Http\JsonResponse
    {
        $status = $request->input('status', '');

        $name = $request->input('name', '');
        $value = $request->input('value', '');
        $pk = $request->input('pk', 0);
        if ($pk) {
            if ($name == 'category_name' && mb_strlen($value, 'utf8') > 4) {
                return response()->json([
                    'status' => false,
                    'message' => "分类名称（最多可输入4个字）",
                ]);
            }
            $result = AlbumCategoryModel::updateDataByWhere([$name => $value], ['id' => $pk]);
            if ($result) {
                return response()->json([
                    'status' => true,
                    'message' => "success",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "修改失败",
                ]);
            }

        } else {
            if ($status && $id > 0) {
                AlbumCategoryModel::updateDataByWhere(['status' => $status], ['id' => $id]);

                return response()->json([
                    'status' => true,
                    'message' => "success",
                ]);
            } else {
                return response()->json([
                    'status' => false,
                    'message' => "修改失败",
                ]);
            }
        }
    }


    public function index(Request $request, Content $content)
    {
        Admin::script($this->indexScript());
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $where['status[!]'] = AlbumCategoryModel::STATUS_DELETE;
        $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize,];
        $where['ORDER'] = ['sort' => 'ASC'];

        $list = AlbumCategoryModel::selectByWhere($where);
        $data = [];
        if ($list) {
            foreach ($list as $item) {
                $albumIds = array_unique(AlbumCategoryRelateModel::selectByWhere([
                    'category_id' => $item['id'],
                    'status' => AlbumCategoryRelateModel::STATUS_NORMAL,
                ], 'album_id'));
                $item['album_list'] = [];
                if(!empty($albumIds)){
                    $albumList = AlbumListModel::selectByWhere([
                        'album_id' => $albumIds,
                        'status' => AlbumListModel::STATS_LIST_PUBLIC_SHOW_MAP,
                        'quality' => [AlbumListModel::QUALITY_GOOD, AlbumListModel::QUALITY_EXCELLENT],
                        'ORDER' => ['publish_time' => 'DESC'],
                    ]);
                    if ($albumList) {
                        $item['album_list'] = FormatAlbumService::_formatAlbumList($albumList);
                    }
                    $item['album_count'] = count($item['album_list']);
                    $data[] = $item;
                }
            }
        }

        unset($where['LIMIT']);
        $total = AlbumCategoryModel::count($where);

        //查询标签列表
        $gridModel = new pGridDataModel($data, $total, ['perPage' => $pageSize]);
        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableCreateButton();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->expand();//默认展开
            });

            $grid->column('id', '分类id')->sort();
            $grid->column('category_name', '分类名称')->editable();
            $grid->column('tag_name', '关联的清单标签');
            $grid->column('album_count', '关联的清单数量')->modal('关联清单列表', function () {
                $data = [];
                if ($this->album_list) {
                    foreach ($this->album_list as $item) {
                        if (isset($item['album_info']) && !empty($item['album_info'])) {
                            $data[] = [
                                "album_id" => $item['album_info']['album_id'],
                                "title" => $item['album_info']['title'],
                                "uid" => $item['album_info']['uid'],
                                "status" => AlbumListModel::STATUS_MAP[$item['album_info']['status']],
                                "wiki_count" => $item['album_info']['wiki_count'],
                                "joiner_num" => $item['album_info']['joiner_num'],
                                "quality" => AlbumListModel::QUALITY_MAP[$item['album_info']['quality']] ?? '暂无质量',
                            ];
                        }
                    }
                }

                return new Table(['清单id', '标题', 'uid', '清单状态', '关联商品数量', 'pv', '质量'], $data);
            });
            $grid->column('status', '展示状态')->switch([
                'on' => ['value' => AlbumCategoryModel::STATUS_NORMAL, 'text' => '展示', 'color' => 'primary'],
                'off' => ['value' => AlbumCategoryModel::STATUS_HIDE, 'text' => '隐藏', 'color' => 'default'],
            ]);
            $grid->column('addtime', '添加时间');
            $grid->column('edittime', '更新时间');
            $grid->column('admin_id', '操作人')->display(function () {
                return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '-';
            });
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('&nbsp;&nbsp;<a class="fa" href="'.url('admin/album/category/create?category_id='.$actions->row->id).'">编辑</a>');
                $actions->append('&nbsp;&nbsp;<a class="act fa del-category" href="javascript:;"  data-category_id="'.$actions->row->id.'" data-action="del-category">删除</a>');
            });

        });

        $tab = new Tab();
        $tab->add('清单分类管理', $grid->render(), true);
        $tab->addLink('创建分类', url("/admin/album/category/create"), false);
        $content->row($tab);

        return $content
            ->header("发现好物 | 清单分类管理");
    }

    private function indexScript()
    {
        return <<<EOF
        $('.del-category').unbind('click').click(function() {
            var category_id = $(this).data('category_id');
            let act= $(this).data('action');
            swal({
                title: "确认要删除吗，此操作不可逆!!!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function() {
                    $.ajax({
                        method: 'post',
                        url: '/admin/album/category/act?category_id=' + category_id+'&act='+act,
                        success: function (data) {
                            console.log(data);
                            $.pjax.reload('#pjax-container');
                            if(data.code){
                                swal(data.msg, '', 'success');
                            }else{
                                swal(data.msg, '', 'error');
                            }
                        }
                    });
                }
            });
        });
EOF;
    }

    public function sort(Request $request)
    {
        $sortInfo = $request->input('sort');
        if ($sortInfo) {
            foreach ($sortInfo as $categoryId => $sort) {
                AlbumCategoryModel::updateDataByWhere(['sort' => $sort], ['id' => $categoryId]);
            }
        }
    }

    public function create(Content $content, Request $request): Content
    {
        $categoryId = $request->input('category_id');
        $data = [];
        $title = '创建分类';
        $tagList = AlbumListService::getTagList();
        if ($categoryId) {
            $tags = [];
            $data = AlbumCategoryModel::getByWhere('*', ['id' => $categoryId]);
            if ($data['tag_name']) {
                foreach ($tagList as $item) {
                    if (in_array(explode('|', $item)[1], explode(',', $data['tag_name']))) {
                        $tags[$item] = $item;
                    }
                }
            }
            $data['tag_list'] = $tags;
            $title = '编辑分类';
        }
        $tagList = array_combine($tagList, $tagList);
        $form = new Form($data);
        $form->hidden('id');
        $form->text('category_name',
            '分类名称')->required()->placeholder('最多可输入4个字符，新添加的分类状态默认为隐藏')->help('最多可输入4个字符，新添加的分类状态默认为隐藏');
        $form->multipleSelect('tag_list', '关联的清单标签')->options($tagList);

        $form->confirm('确定提交吗？', 'add');
        $form->action('/admin/album/category/save');

        $tab = new Tab();
        $tab->add($title, $form->render(), true);
        $tab->addLink('清单分类管理', url("/admin/album/category/index"), false);
        $content->row($tab);

        return $content
            ->header("清单分类管理 | $title");
    }

    public function save(Request $request): RedirectResponse
    {
        $categoryId = $request->input('id', '');
        $categoryName = $request->input('category_name', '');
        $tagList = array_filter($request->input('tag_list', []));//标签列表
        try {
            if (mb_strlen($categoryName, 'utf8') > 20) {
                throw new Exception('分类名称（最多可输入4个字）');
            }

            $tagNames = [];
            if (!empty($tagList)) {
                foreach ($tagList as $tagInfo) {
                    $tagNames [] = explode('|', $tagInfo)[1] ?? '';
                }
            }
            $data = [
                'category_name' => $categoryName,
                'tag_name' => implode(',', $tagNames),
                'admin_id' => Admin::user()->id,
            ];
            $result = AlbumCategoryService::saveAlbumCategory($data, $categoryId);
            if (!$result) {
                throw new Exception('分类编辑失败');
            }

            return redirect('/admin/album/category/index');
        } catch (Exception $e) {
            Log::error('活动编辑失败', $e->getMessage());
            $error = new MessageBag([
                'title' => '编辑失败,'.$e->getMessage(),
            ]);

            return back()->with(compact('error'));
        }

    }

    public function act(Request $request): \Illuminate\Http\JsonResponse
    {
        $categoryId = $request->input('category_id', 0);
        $act = $request->input('act', '');
        $code = 1;
        try {
            switch ($act) {
                case 'del-category';
                    $delCategory = AlbumCategoryModel::updateDataByWhere([
                        'status' => AlbumCategoryModel::STATUS_DELETE,
                        'admin_id' => Admin::user()->id,
                    ], ['id' => $categoryId]);
                    $delCategoryRelate = AlbumCategoryRelateModel::updateDataByWhere(['status' => AlbumCategoryRelateModel::STATUS_DELETE],
                        ['category_id' => $categoryId]);
                    if ($delCategory && $delCategoryRelate) {
                        $msg = '后台操作删除成功';
                    } else {
                        $msg = '后台操作删除失败';
                    }

                    break;
                default;
                    $msg = 'nothing ';

            }
        } catch (\Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
        }

        $response = [
            'code' => $code,
            'msg' => $msg,
        ];

        return response()->json($response);
    }

}